package com.chw.utils.email;


import com.chw.common.ChangLiang;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

@Component
public class ToEmail {
    public static void main(String[] args) throws MessagingException, UnsupportedEncodingException {
        sendMail("2982950550@qq.com", "是我你*", "三儿");
    }

    /**
     * 发送验证码
     *
     * @param
     * @throws Exception
     */
    public static void sendMail(String to, String content, String title) throws MessagingException, UnsupportedEncodingException {
        Properties prop = new Properties();
        // 开启debug调试，以便在控制台查看
        prop.setProperty("mail.debug", "true");

        // 设置邮件服务器主机名
        prop.setProperty("mail.host", "smtp.qq.com");
        // 发送服务器需要身份验证
        prop.setProperty("mail.smtp.auth", "true");
        // 发送邮件协议名称
        prop.setProperty("mail.transport.protocol", "smtp");
        //根据配置创建会话对象，对于和邮件服务器交互
        Session session = Session.getDefaultInstance(prop);
        //创建邮件对象
        MimeMessage message = new MimeMessage(session);
        //设置发件人
        message.setFrom(new InternetAddress("2982950550@qq.com",ChangLiang.EMAILNAME, "utf-8"));
        //设置收件人
        message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(to, "名称", "UTF-8"));
        //Subject：邮件主题
        message.setSubject(title, "UTF-8");
        //邮件正文
        message.setContent(content, "text/html;charset=UTF-8");
        //发送时间
        message.setSentDate(new Date());
        //编辑好后得到发送对象
        Transport transport = session.getTransport();
        //连接
        transport.connect("2982950550@qq.com", "thzpoudytnljdfdf");
        //发送邮件
        transport.sendMessage(message, message.getAllRecipients());
    }


}
